import { dom } from '@knno/dom';
import { button } from '@knno/ui/button';
import { Grid, grid } from '@knno/ui/grid';
import { bar } from './index.css';

function range(begin: number, end: number, step = 1) {
	return {
		[Symbol.iterator]: function* generateRange() {
			let x = begin - step;
			while (x < end - step) yield (x += step);
		},
	};
}

function genText() {
	return [...range(1, Math.random() * 30 + 1)]
		.map(() => {
			const v = 0x4e00 + Math.floor(Math.random() * (0x9fa5 - 0x4e00));
			return String.fromCharCode(v);
		})
		.reduce((p, v) => p + v);
}

export function renderInfiniteGrid() {
	let tb: Grid;

	function addColumns() {
		tb.columns([
			{ title: '列1', key: 0, align: 'center', sortable: true, width: '200px', resizable: true },
			{ title: '列2', key: 1, sortable: true, width: '10%', resizable: true },
			{ title: '列3', key: 2, align: 'right', width: '10%', resizable: true },
			{ title: '列4', key: 3, width: '10%' },
			{ title: '列5', key: 4, width: '10%' },
			{ title: '列6', key: 4, width: '15%', resizable: true },
			{ title: '列7', key: 4, width: '15%', resizable: true },
		]);
	}

	let lines = 0;
	function addData(more: boolean) {
		const result: any[] = [];
		for (let i = 0; i < 50; i++) {
			lines++;
			const row = [];
			row.push(lines);
			row.push(genText());
			for (let j = 1; j < 4; j++) {
				row.push('text content ' + j);
			}
			result.push(row);
		}
		result.push({ section: '加载更多...' });
		console.log('data generated!');
		if (more) {
			setTimeout(() => {
				if (tb.rows().length > 0) {
					tb.rows().length -= 1;
				}
				tb.appendRows(result);
			}, 1000);
		} else {
			tb.rows(result);
		}
	}

	return [
		dom.h2().text('无限加载'),
		dom.div(bar).append(
			button()
				.type('danger')
				.text('删除数据')
				.on('click', () => {
					lines = 0;
					tb.rows([]);
				})
		),
		grid()
			.section({
				key: 'section',
			})
			.ref((t) => {
				tb = t;
				addColumns();
				addData(false);
			})
			.on('scrollbottom', () => {
				const st = tb.scrollTop();
				console.log('scrollTop:', st);
				addData(true);
				// tb.scrollTop(st);
			}),
	];
}
